package Servlet.Login;

import bean.userBean;
import dao.Db;
import util.Md5;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;

@WebServlet(name = "LoginServlet", value = "/LoginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.sendRedirect("index.jsp");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String msg = "";
        String url = "novelListManagerServlet";
        HttpSession session = request.getSession();

        try {
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            String code 	= request.getParameter("code");			//输入的验证码

            if (username == null || username.trim().equals("")) {
                msg = "请输入用户名！";
                return;												//即使这里有return，也会在程序结束之前执行finally中的代码
            }
            username = username.trim();

            if (password == null || password.equals("")) {
                msg = "请输入密码！";
                return;
            }

            if (code == null || code.trim().equals("")) {			//对输入的验证码进行校验
                msg = "@RefreshCode:请输入验证码！";
                return;
            }
            code = code.trim().toLowerCase();						//转换为小写字母

            if (session.getAttribute("code") == null) {				//session中的验证码
                msg = "@RefreshCode:验证码已过期。请重新输入。";
                return;
            }

            String codeSession = session.getAttribute("code").toString();
            codeSession = codeSession.toLowerCase();

            if (code.equals(codeSession) == false) {
                msg = "@RefreshCode:您输入的验证码错误。请重新输入。";
                return;
            }

            String salt = "login_fdsfj45349fd";						//加点料（放点盐）。此料应与登录页index.jsp中加的料相同
            password = Md5.getMd5(username + password + salt);		//对用户名+密码+料进行MD5加密
            System.out.println(password);
            Db db = new Db();										//新建实例（该实例实现了数据的增删改查）
            String sql = "";
            ResultSet rs = null;

            sql = "select * from tb_user where userName=? and password=?";
            rs = db.select(sql, username, password);

            userBean user=new userBean();           //创建user对象

            if (rs == null) {
                msg = "数据库操作发生错误！";
                return;
            }

            if (rs.next() == false)	{						//尝试读取下一条记录，如果未读到记录
                db.close();
                msg = "登录失败！您输入的用户名或者密码不正确。";
                return;
            }
            //--------往下：能查询到记录

            user.setUserNumber(rs.getString("userNumber"));			//读取字段
            user.setUserName(rs.getString("userName"));			//读取字段
            user.setUserType(rs.getString("userType"));			//读取字段

            db.close();										//用完及时关闭与数据库连接

            session.setMaxInactiveInterval(20 * 60);		//有效时长20分钟。由于在生成验证码时设置的时长是60秒
            session.setAttribute("user", user); 		//用户id，添加到session

            //--------由于index.jsp使用了ajax，这里无法实现网页重定向或转发
            //response.sendRedirect(url);										//网页重定向
            //request.getRequestDispatcher(url).forward(request, response);		//转发
            //return;
            msg = "@Redirect:" + url;						//增加@Redirect用于通知ajax进行网页转向（自创协议）

        } catch (Exception e) {
            msg = "系统发生错误。";
            e.printStackTrace();							//输出异常信息到控制台
        } finally {
            out.print(msg);									//输出信息到页面
        }
    }
}
